package org.zlb.algorithm.distance;

public class Hamming {

    /**
     * 汉明距离，对应位不同的数量，多用于图像像素
     * @param s1
     * @param s2
     * @return
     */
    public static int d(String s1, String s2) {
        if (s1 == null && s2 == null)
            return 0;
        if (s1 == null && s2 != null)
            return s2.length();
        if (s1 != null && s2 == null)
            return s1.length();
        
        int d = Math.abs(s1.length() - s2.length());
        int n = Math.min(s1.length(), s2.length());
        
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        for (int i=0; i<n; i++) {
            if (c1[i] != c2[i]) {
                d ++;
            }
        }
        
        return d;
    }
}
